<template>
  <div class="go-tableS2">
   <div v-if="s2DataConfig" ref="containerIdRef" :id="containerId" style="width: auto; height: 100%; overflow: auto" />
          <div class="aic jcc " v-else>
            <n-result status="404" title="字段拖入维度自动生成图表"> </n-result>
          </div>
           <n-pagination
            :page-sizes="[20, 50, 100]"
            v-model:page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-count="pagination.count"
            show-size-picker
            :on-update:page="handlePage"
            :on-update:page-size="handlePageSize"
          />
    <filterHeader v-model="showModalConfigFilter"></filterHeader>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import Datatable from './component/datatable.vue'
import filterHeader from '@/views/Bi/editReport/components/filterHeader.vue'
import { FlashOutline } from '@vicons/ionicons5'
import { useChartEditStoreBi } from '@/views/Bi/store/chartEditStore/chartEditStoreBi'
import { getUUID } from '@/utils'
const containerId = getUUID()
const props = defineProps({
  s2DataConfig: {
    type: Object,
    required: true
  },
   type: {
    type: String,
    required: true
  },
   styles: {
    type: Object,
    required: false
  }
})
import { debounce,cloneDeep } from 'lodash'
import { PivotSheet, TableSheet, S2Event, EXTRA_FIELD,

} from '@antv/s2'
import { dataTool } from 'echarts'
import { useThemeVars } from 'naive-ui'
import { useBiUtils } from '@/views/Bi/hooks/BiUtils'
import { ComponentBiDataType } from '@/enums/editReportEnum'

const superfluousHeight = 140 + 38
const showModalConfigFilter = ref(false)
let s2: any = null

// 2. 配置数据
const s2DataConfig: any = ref()
// const chartEditStoreBi = useChartEditStoreBi()
// const targetData: any = computed(() => {
//   if (chartEditStoreBi.getTargetDataBase) {
//     setTimeout(() => {
//       nextTick(() => {
//            //更新配置文件 s2DataConfig
//       if(!s2){
//       s2DataConfig.value.fields = chartEditStoreBi.getTargetDataBase?.fields
//        s2DataConfig.value.meta = chartEditStoreBi.getTargetDataBase?.meta
//       init(chartEditStoreBi.getTargetDataBase?.data)
//       }else{
//           s2DataConfig.value.data = chartEditStoreBi.getTargetDataBase?.data
//            s2DataConfig.value.fields = chartEditStoreBi.getTargetDataBase?.fields
//        s2DataConfig.value.meta = chartEditStoreBi.getTargetDataBase?.meta
//   s2.setDataCfg(s2DataConfig.value)
//   s2.render()
//       }

//       })
//     }, 500);
//   }
//   return chartEditStoreBi.getTargetDataBase
// })
watch(
  () => props.s2DataConfig,
  (val: any) => {
    if (val&&val.id) {
      let copyData = cloneDeep(val) 
      for (const key in copyData.fields) {
        if (Object.prototype.hasOwnProperty.call(copyData.fields, key)) {
          const element = copyData.fields[key];
          copyData.fields[key] = element.map((res:any)=>res.field)
        }
      }
      s2DataConfig.value = copyData
      nextTick(() => {
        //更新配置文件 s2DataConfig
        if (!s2) {
          init()
        } else {
          s2.setDataCfg(s2DataConfig.value)
          s2.render()
        }
      })
    }
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.type,
  (val: any) => {
   
     nextTick(() => {
        //更新配置文件 s2DataConfig
        clearContainerId()
          init()
      })
  },
  
)
const pagination = ref({
  pageSize: 20,
  current: 1,
  total: 8,
  count: Math.ceil(8 / 2)
})

const { useThemeS2Table } = useBiUtils()
//监听变化
watch(()=>props.styles,(style:any)=>{
if (s2) {
         debounceRender(style.w-10, style.h-60)
        } 
},{
  deep:true,
})
const clearContainerId = () =>{
  nextTick(()=>{
    const container: any = document.getElementById(containerId)
    container.removeChild();
  })
}
  const debounceRender = debounce((width, height) => {
    s2.changeSheetSize(width, height)
    s2.render(false) // 不重新加载数据
  }, 200)
  const containerIdRef = ref("")
const init = () => {
  // 1. 准备数据
  const container: any = document.getElementById(containerId)
  // 3. 添加配置
  // 设置自定义 `icon` 的展示条件
  const headerActionIcons = [
    {
      // 选择icon,可以是 S2 自带的，也可以是自定义的 icon
      iconNames: ['customFunnel'],
      // 通过 belongsCell + displayCondition 设置 icon 的展示位置
      belongsCell: 'colCell',
      // icon 点击之后的执行函数
      action: (props: any) => {
        const { meta, event } = props
        console.log(props)
        showModalConfigFilter.value = true
      }
    }
  ]
  const filterIcon = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 512 512"><path d="M296 464a23.88 23.88 0 0 1-7.55-1.23L208.3 436.1a23.92 23.92 0 0 1-16.3-22.78V294.11a.44.44 0 0 0-.09-.13L23.26 97.54A30 30 0 0 1 46.05 48H466a30 30 0 0 1 22.79 49.54L320.09 294a.77.77 0 0 0-.09.13V440a23.93 23.93 0 0 1-24 24z" fill="currentColor"></path></svg>`
  console.log(container.offsetwidth, 'container.offsetwidth')
  const s2Options = {
    width: container.offsetWidth,
    height: container.offsetHeight,
    // 关闭默认icon
    showDefaultHeaderActionIcon: false,
    tooltip: {
      showTooltip: true
    },
    // 自定义 icon
    customSVGIcons: [
      {
        name: 'customFunnel',
        svg: filterIcon
      }
    ],
    headerActionIcons
  }
  let Sheet:any = PivotSheet;
  if(props.type == ComponentBiDataType.PIVOT_TABLE){
    Sheet = PivotSheet
  }else   if(props.type == ComponentBiDataType.TABLE){
    Sheet = TableSheet
  }
  s2 = new Sheet(container, s2DataConfig.value, s2Options)
  const customTheme = useThemeS2Table()

  // name 可为 default, colorful, gray
  s2.setTheme(customTheme)


  new ResizeObserver(([entry] = []) => {
    const [size] = entry.borderBoxSize || []
    const container: any = containerIdRef.value
    console.log(container.offsetWidth)
    debounceRender(container.offsetWidth, container.offsetHeight)
  }).observe(document.body) // 通过监听 document.body 来实现监听窗口大小变化
  s2.render(true)
}

const handlePage = (page: number) => {
  pagination.value.current = page
  let data = [
    {
      province: '浙江',
      city: '杭州',
      type: '家具',
      sub_type: '桌子',
      price: '1'
    },
    {
      province: '浙江',
      city: '杭州',
      type: '家具',
      sub_type: '沙发',
      price: '2'
    },
    {
      province: '浙江',
      city: '杭州',
      type: '办公用品',
      sub_type: '笔',
      price: '3'
    },
    {
      province: '浙江',
      city: '杭州',
      type: '办公用品',
      sub_type: '纸张',
      price: '4'
    }
  ]
  data = data.map((res: any) => {
    res.city = res.city + page
    return res
  })

  handleInit(data)
}
const handlePageSize = (page: number) => {
  pagination.value.pageSize = page
}
const handleInit = (data: any) => {
  s2DataConfig.value.data = data
  s2.setDataCfg(s2DataConfig.value)
  s2.render()
}
onMounted(() => {})
//删除 模块
const handleDeleteModel = (item: any) => {}
</script>

<style lang="scss" scoped>
// #container {
//   width: 100%;
//   height: 100%;
// }
@include go(tableS2) {
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-rows: 1fr 28px;
}
</style>
